package xyz.xtgl.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.web.context.SecurityContextPersistenceFilter;
import xyz.xtgl.config.helper.CustomTokenExceptionEntryPoint;
import xyz.xtgl.config.helper.TokenAutnenticationFilter;
import xyz.xtgl.oahth2.config.constant.GlobalConstant;

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Autowired
    private TokenStore tokenStore;

    @Bean
    public CustomTokenExceptionEntryPoint customTokenExceptionEntryPoint(){
        return new CustomTokenExceptionEntryPoint();
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources
                .authenticationEntryPoint(customTokenExceptionEntryPoint())
                .resourceId(GlobalConstant.XTGL_WEB_MERCHANT_RESOURCES_ID)//资源 id
                .tokenStore(tokenStore)
                .stateless(true);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        TokenAutnenticationFilter filter = new TokenAutnenticationFilter();
        http.addFilterBefore(filter, SecurityContextPersistenceFilter.class)
            .authorizeRequests()
            //views 所有文件都可以执行
            .antMatchers(
                    "/lib/**","/js/**","/style/**","/views/**","/**/index.html","/**/login.html","/images/**","/download/**")
                .permitAll()
            .anyRequest()
                .access("#oauth2.hasScope('"+ GlobalConstant.XTGL_WEB_MERCHANT_SCOPE +"')")
            .and().headers().frameOptions().disable()
            .and().csrf().disable()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        super.configure(http);
    }
}
